<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: Coupon.php
 * Date: 2017/1/18
 * Time: 0:08
 */
namespace app\api\model\page\shop;

use app\api\model\dao\Coupon;
use think\Validate;
use app\library\PageBase;
use app\library\Error;

class AddCoupon extends PageBase
{
    public function __construct()
    {
        parent::__construct();
    }

    public function excute($param)
    {
        if (false === $this->checkToken($param)) {
            //return $this->getRes(Error::ERR_NO_AUTH);
        }
        $result = $this->check($param);
        if (true !== $result) {
            return $this->getRes(Error::ERR_PARAM, $result);
        }
        if ($param['end_time'] <= $param['start_time']) {
            return $this->getRes(Error::ERR_PARAM, '结束时间必须大于开始时间');
        }
        $param['start_time'] = strtotime($param['start_time']);
        $param['end_time'] = strtotime($param['end_time']);

        $objModel = new Coupon();
        $ret = $objModel->addCoupon($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }
        return $this->getRes();
    }

    public function check($param)
    {
        $rule = [
            'coupon_name' => 'require|max:25',
            'price' => 'require|float|between:0,9999',
            'base_price' => 'require|float|between:0,9999',
            'type' => 'require',
            'description' => 'require',
            'amount' => 'require',
            'start_time' => 'require|date',
            'end_time' => 'require|date',
        ];
        $msg = [
            'coupon_name.require' => '优惠券名称必须',
            'coupon_name.max' => '名称最多不能超过25个字符',
            'price.require' => '优惠券金额必须',
            'price.float' => '优惠券金额必须包含两位小数',
            'base_price.require' => '优惠券起用金额必须',
            'base_price.float' => '优惠券启用金额必须包含两位小数',
            'type.require' => '优惠券类型必须',
            'description.require' => '优惠券描述必须',
            'amount.require' => '优惠券数量必须',
            'start_time.require' => '优惠券开始使用时间必须',
            'end_time.require' => '优惠券结束使用时间必须',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return $result;
    }

}